import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");

        //服务器从客户端获取cookie，返回数组，说明存在多个cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            Cookie c = cookie;
            //获取cookie的键，判断是否存在
            if(c.getName().equals("lastLoginTime")){
                //获取cookie对应键的值
                resp.getWriter().print("您上一次访问本站的时间为：" + c.getValue());
            }else {
                resp.getWriter().print("这是您第一次访问本站");
                //服务给客户端响应返回一个cookie
                Cookie cookie1 = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
                //设置过期时间为1天，即使浏览器关掉重新打开浏览器，cookie依旧存在
                cookie1.setMaxAge(24 * 60 * 60);
                //新增cookie
                resp.addCookie(cookie1);
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
